home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2002 November / SGI IRIX Base Documentation 2002 November.iso / usr / share / catman / u_man / cat1 / perlembed.z / perlembed
Encoding:
Text File  |  2002-10-03  |  49.4 KB  |  1,387 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlembed - how to embed perl in your C program
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      PPPPRRRREEEEAAAAMMMMBBBBLLLLEEEE
  13.  
  14.      Do you want to:
  15.  
  16.      UUUUsssseeee CCCC ffffrrrroooommmm PPPPeeeerrrrllll????
  17.           Read the _p_e_r_l_x_s_t_u_t manpage, the _p_e_r_l_x_s manpage, the _h_2_x_s manpage,
  18.           and the _p_e_r_l_g_u_t_s manpage.
  19.  
  20.      UUUUsssseeee aaaa UUUUnnnniiiixxxx pppprrrrooooggggrrrraaaammmm ffffrrrroooommmm PPPPeeeerrrrllll????
  21.           Read about back-quotes and about system and exec in the _p_e_r_l_f_u_n_c
  22.           manpage.
  23.  
  24.      UUUUsssseeee PPPPeeeerrrrllll ffffrrrroooommmm PPPPeeeerrrrllll????
  25.           Read about the do entry in the _p_e_r_l_f_u_n_c manpage and the eval entry
  26.           in the _p_e_r_l_f_u_n_c manpage and the require entry in the _p_e_r_l_f_u_n_c
  27.           manpage and the use entry in the _p_e_r_l_f_u_n_c manpage.
  28.  
  29.      UUUUsssseeee CCCC ffffrrrroooommmm CCCC????
  30.           Rethink your design.
  31.  
  32.      UUUUsssseeee PPPPeeeerrrrllll ffffrrrroooommmm CCCC????
  33.           Read on...
  34.  
  35.      RRRROOOOAAAADDDDMMMMAAAAPPPP
  36.  
  37.      the section on _C_o_m_p_i_l_i_n_g _y_o_u_r _C _p_r_o_g_r_a_m
  38.  
  39.      the section on _A_d_d_i_n_g _a _P_e_r_l _i_n_t_e_r_p_r_e_t_e_r _t_o _y_o_u_r _C _p_r_o_g_r_a_m
  40.  
  41.      the section on _C_a_l_l_i_n_g _a _P_e_r_l _s_u_b_r_o_u_t_i_n_e _f_r_o_m _y_o_u_r _C _p_r_o_g_r_a_m
  42.  
  43.      the section on _E_v_a_l_u_a_t_i_n_g _a _P_e_r_l _s_t_a_t_e_m_e_n_t _f_r_o_m _y_o_u_r _C _p_r_o_g_r_a_m
  44.  
  45.      the section on _P_e_r_f_o_r_m_i_n_g _P_e_r_l _p_a_t_t_e_r_n _m_a_t_c_h_e_s _a_n_d _s_u_b_s_t_i_t_u_t_i_o_n_s _f_r_o_m
  46.      _y_o_u_r _C _p_r_o_g_r_a_m
  47.  
  48.      the section on _F_i_d_d_l_i_n_g _w_i_t_h _t_h_e _P_e_r_l _s_t_a_c_k _f_r_o_m _y_o_u_r _C _p_r_o_g_r_a_m
  49.  
  50.      the section on _M_a_i_n_t_a_i_n_i_n_g _a _p_e_r_s_i_s_t_e_n_t _i_n_t_e_r_p_r_e_t_e_r
  51.  
  52.      the section on _M_a_i_n_t_a_i_n_i_n_g _m_u_l_t_i_p_l_e _i_n_t_e_r_p_r_e_t_e_r _i_n_s_t_a_n_c_e_s
  53.  
  54.      the section on _U_s_i_n_g _P_e_r_l _m_o_d_u_l_e_s, _w_h_i_c_h _t_h_e_m_s_e_l_v_e_s _u_s_e _C _l_i_b_r_a_r_i_e_s, _f_r_o_m
  55.      _y_o_u_r _C _p_r_o_g_r_a_m
  56.  
  57.      the section on _E_m_b_e_d_d_i_n_g _P_e_r_l _u_n_d_e_r _W_i_n_3_2
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  71.  
  72.  
  73.  
  74.      CCCCoooommmmppppiiiilllliiiinnnngggg yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  75.  
  76.      If you have trouble compiling the scripts in this documentation, you're
  77.      not alone.  The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY THE SAME
  78.      WAY THAT YOUR PERL WAS COMPILED.  (Sorry for yelling.)
  79.  
  80.      Also, every C program that uses Perl must link in the _p_e_r_l _l_i_b_r_a_r_y.
  81.      What's that, you ask?  Perl is itself written in C; the perl library is
  82.      the collection of compiled C programs that were used to create your perl
  83.      executable (/_u_s_r/_b_i_n/_p_e_r_l or equivalent).  (Corollary: you can't use Perl
  84.      from your C program unless Perl has been compiled on your machine, or
  85.      installed properly--that's why you shouldn't blithely copy Perl
  86.      executables from machine to machine without also copying the _l_i_b
  87.      directory.)
  88.  
  89.      When you use Perl from C, your C program will--usually--allocate, "run",
  90.      and deallocate a _P_e_r_l_I_n_t_e_r_p_r_e_t_e_r object, which is defined by the perl
  91.      library.
  92.  
  93.      If your copy of Perl is recent enough to contain this documentation
  94.      (version 5.002 or later), then the perl library (and _E_X_T_E_R_N._h and _p_e_r_l._h,
  95.      which you'll also need) will reside in a directory that looks like this:
  96.  
  97.          /usr/local/lib/perl5/your_architecture_here/CORE
  98.  
  99.      or perhaps just
  100.  
  101.          /usr/local/lib/perl5/CORE
  102.  
  103.      or maybe something like
  104.  
  105.          /usr/opt/perl5/CORE
  106.  
  107.      Execute this statement for a hint about where to find CORE:
  108.  
  109.          perl -MConfig -e 'print $Config{archlib}'
  110.  
  111.      Here's how you'd compile the example in the next section, the section on
  112.      _A_d_d_i_n_g _a _P_e_r_l _i_n_t_e_r_p_r_e_t_e_r _t_o _y_o_u_r _C _p_r_o_g_r_a_m, on my Linux box:
  113.  
  114.          % gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
  115.          -I/usr/local/lib/perl5/i586-linux/5.003/CORE
  116.          -L/usr/local/lib/perl5/i586-linux/5.003/CORE
  117.          -o interp interp.c -lperl -lm
  118.  
  119.      (That's all one line.)  On my DEC Alpha running old 5.003_05, the
  120.      incantation is a bit different:
  121.  
  122.          % cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include
  123.          -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
  124.          -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
  125.          -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  137.  
  138.  
  139.  
  140.      How can you figure out what to add?  Assuming your Perl is post-5.001,
  141.      execute a perl -V command and pay special attention to the "cc" and
  142.      "ccflags" information.
  143.  
  144.      You'll have to choose the appropriate compiler (_c_c, _g_c_c, et al.) for your
  145.      machine: perl -MConfig -e 'print $Config{cc}' will tell you what to use.
  146.  
  147.      You'll also have to choose the appropriate library directory
  148.      (/_u_s_r/_l_o_c_a_l/_l_i_b/...) for your machine.  If your compiler complains that
  149.      certain functions are undefined, or that it can't locate -_l_p_e_r_l, then you
  150.      need to change the path following the -L.  If it complains that it can't
  151.      find _E_X_T_E_R_N._h and _p_e_r_l._h, you need to change the path following the -I.
  152.  
  153.      You may have to add extra libraries as well.  Which ones?  Perhaps those
  154.      printed by
  155.  
  156.         perl -MConfig -e 'print $Config{libs}'
  157.  
  158.      Provided your perl binary was properly configured and installed the
  159.      EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd module will determine all of this information for you:
  160.  
  161.         % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  162.  
  163.      If the EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd module isn't part of your Perl distribution, you
  164.      can retrieve it from http://www.perl.com/perl/CPAN/modules/by-
  165.      module/ExtUtils::Embed.  (If this documentation came from your Perl
  166.      distribution, then you're running 5.004 or better and you already have
  167.      it.)
  168.  
  169.      The EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd kit on CPAN also contains all source code for the
  170.      examples in this document, tests, additional examples and other
  171.      information you may find useful.
  172.  
  173.      AAAAddddddddiiiinnnngggg aaaa PPPPeeeerrrrllll iiiinnnntttteeeerrrrpppprrrreeeetttteeeerrrr ttttoooo yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  174.  
  175.      In a sense, perl (the C program) is a good example of embedding Perl (the
  176.      language), so I'll demonstrate embedding with _m_i_n_i_p_e_r_l_m_a_i_n._c, included in
  177.      the source distribution.  Here's a bastardized, nonportable version of
  178.      _m_i_n_i_p_e_r_l_m_a_i_n._c containing the essentials of embedding:
  179.  
  180.          #include <EXTERN.h>               /* from the Perl distribution     */
  181.          #include <perl.h>                 /* from the Perl distribution     */
  182.  
  183.          static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/
  184.  
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  203.  
  204.  
  205.  
  206.          int main(int argc, char **argv, char **env)
  207.          {
  208.              my_perl = perl_alloc();
  209.              perl_construct(my_perl);
  210.              perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
  211.              perl_run(my_perl);
  212.              perl_destruct(my_perl);
  213.              perl_free(my_perl);
  214.          }
  215.  
  216.      Notice that we don't use the env pointer.  Normally handed to perl_parse
  217.      as its final argument, env here is replaced by NULL, which means that the
  218.      current environment will be used.
  219.  
  220.      Now compile this program (I'll call it _i_n_t_e_r_p._c) into an executable:
  221.  
  222.          % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  223.  
  224.      After a successful compilation, you'll be able to use _i_n_t_e_r_p just like
  225.      perl itself:
  226.  
  227.          % interp
  228.          print "Pretty Good Perl \n";
  229.          print "10890 - 9801 is ", 10890 - 9801;
  230.          <CTRL-D>
  231.          Pretty Good Perl
  232.          10890 - 9801 is 1089
  233.  
  234.      or
  235.  
  236.          % interp -e 'printf("%x", 3735928559)'
  237.          deadbeef
  238.  
  239.      You can also read and execute Perl statements from a file while in the
  240.      midst of your C program, by placing the filename in _a_r_g_v[_1] before
  241.      calling _p_e_r_l__r_u_n.
  242.  
  243.      CCCCaaaalllllllliiiinnnngggg aaaa PPPPeeeerrrrllll ssssuuuubbbbrrrroooouuuuttttiiiinnnneeee ffffrrrroooommmm yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  244.  
  245.      To call individual Perl subroutines, you can use any of the ppppeeeerrrrllll____ccccaaaallllllll____****
  246.      functions documented in the _p_e_r_l_c_a_l_l manpage.  In this example we'll use
  247.      perl_call_argv.
  248.  
  249.      That's shown below, in a program I'll call _s_h_o_w_t_i_m_e._c.
  250.  
  251.          #include <EXTERN.h>
  252.          #include <perl.h>
  253.  
  254.          static PerlInterpreter *my_perl;
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  269.  
  270.  
  271.  
  272.          int main(int argc, char **argv, char **env)
  273.          {
  274.              char *args[] = { NULL };
  275.              my_perl = perl_alloc();
  276.              perl_construct(my_perl);
  277.  
  278.              perl_parse(my_perl, NULL, argc, argv, NULL);
  279.  
  280.              /*** skipping perl_run() ***/
  281.  
  282.              perl_call_argv("showtime", G_DISCARD | G_NOARGS, args);
  283.  
  284.              perl_destruct(my_perl);
  285.              perl_free(my_perl);
  286.          }
  287.  
  288.      where _s_h_o_w_t_i_m_e is a Perl subroutine that takes no arguments (that's the
  289.      _G__N_O_A_R_G_S) and for which I'll ignore the return value (that's the
  290.      _G__D_I_S_C_A_R_D).  Those flags, and others, are discussed in the _p_e_r_l_c_a_l_l
  291.      manpage.
  292.  
  293.      I'll define the _s_h_o_w_t_i_m_e subroutine in a file called _s_h_o_w_t_i_m_e._p_l:
  294.  
  295.          print "I shan't be printed.";
  296.  
  297.          sub showtime {
  298.              print time;
  299.          }
  300.  
  301.      Simple enough.  Now compile and run:
  302.  
  303.          % cc -o showtime showtime.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  304.  
  305.          % showtime showtime.pl
  306.          818284590
  307.  
  308.      yielding the number of seconds that elapsed between January 1, 1970 (the
  309.      beginning of the Unix epoch), and the moment I began writing this
  310.      sentence.
  311.  
  312.      In this particular case we don't have to call _p_e_r_l__r_u_n, but in general
  313.      it's considered good practice to ensure proper initialization of library
  314.      code, including execution of all object DESTROY methods and package END
  315.      {} blocks.
  316.  
  317.      If you want to pass arguments to the Perl subroutine, you can add strings
  318.      to the NULL-terminated args list passed to _p_e_r_l__c_a_l_l__a_r_g_v.  For other
  319.      data types, or to examine return values, you'll need to manipulate the
  320.      Perl stack.  That's demonstrated in the last section of this document:
  321.      the section on _F_i_d_d_l_i_n_g _w_i_t_h _t_h_e _P_e_r_l _s_t_a_c_k _f_r_o_m _y_o_u_r _C _p_r_o_g_r_a_m.
  322.  
  323.  
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  335.  
  336.  
  337.  
  338.      EEEEvvvvaaaalllluuuuaaaattttiiiinnnngggg aaaa PPPPeeeerrrrllll ssssttttaaaatttteeeemmmmeeeennnntttt ffffrrrroooommmm yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  339.  
  340.      Perl provides two API functions to evaluate pieces of Perl code.  These
  341.      are the perl_eval_sv entry in the _p_e_r_l_g_u_t_s manpage and the perl_eval_pv
  342.      entry in the _p_e_r_l_g_u_t_s manpage.
  343.  
  344.      Arguably, these are the only routines you'll ever need to execute
  345.      snippets of Perl code from within your C program.  Your code can be as
  346.      long as you wish; it can contain multiple statements; it can employ the
  347.      use entry in the _p_e_r_l_f_u_n_c manpage, the require entry in the _p_e_r_l_f_u_n_c
  348.      manpage, and the do entry in the _p_e_r_l_f_u_n_c manpage to include external
  349.      Perl files.
  350.  
  351.      _p_e_r_l__e_v_a_l__p_v lets us evaluate individual Perl strings, and then extract
  352.      variables for coercion into C types.  The following program, _s_t_r_i_n_g._c,
  353.      executes three Perl strings, extracting an int from the first, a float
  354.      from the second, and a char * from the third.
  355.  
  356.         #include <EXTERN.h>
  357.         #include <perl.h>
  358.  
  359.         static PerlInterpreter *my_perl;
  360.  
  361.         main (int argc, char **argv, char **env)
  362.         {
  363.             char *embedding[] = { "", "-e", "0" };
  364.  
  365.             my_perl = perl_alloc();
  366.             perl_construct( my_perl );
  367.  
  368.             perl_parse(my_perl, NULL, 3, embedding, NULL);
  369.             perl_run(my_perl);
  370.  
  371.             /** Treat $a as an integer **/
  372.             perl_eval_pv("$a = 3; $a **= 2", TRUE);
  373.             printf("a = %d\n", SvIV(perl_get_sv("a", FALSE)));
  374.  
  375.             /** Treat $a as a float **/
  376.             perl_eval_pv("$a = 3.14; $a **= 2", TRUE);
  377.             printf("a = %f\n", SvNV(perl_get_sv("a", FALSE)));
  378.  
  379.             /** Treat $a as a string **/
  380.             perl_eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
  381.             printf("a = %s\n", SvPV(perl_get_sv("a", FALSE), PL_na));
  382.  
  383.             perl_destruct(my_perl);
  384.             perl_free(my_perl);
  385.         }
  386.  
  387.      All of those strange functions with _s_v in their names help convert Perl
  388.      scalars to C types.  They're described in the _p_e_r_l_g_u_t_s manpage.
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  401.  
  402.  
  403.  
  404.      If you compile and run _s_t_r_i_n_g._c, you'll see the results of using _S_v_I_V()
  405.      to create an int, _S_v_N_V() to create a float, and _S_v_P_V() to create a
  406.      string:
  407.  
  408.         a = 9
  409.         a = 9.859600
  410.         a = Just Another Perl Hacker
  411.  
  412.      In the example above, we've created a global variable to temporarily
  413.      store the computed value of our eval'd expression.  It is also possible
  414.      and in most cases a better strategy to fetch the return value from
  415.      _p_e_r_l__e_v_a_l__p_v() instead.  Example:
  416.  
  417.         ...
  418.         SV *val = perl_eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
  419.         printf("%s\n", SvPV(val,PL_na));
  420.         ...
  421.  
  422.      This way, we avoid namespace pollution by not creating global variables
  423.      and we've simplified our code as well.
  424.  
  425.      PPPPeeeerrrrffffoooorrrrmmmmiiiinnnngggg PPPPeeeerrrrllll ppppaaaatttttttteeeerrrrnnnn mmmmaaaattttcccchhhheeeessss aaaannnndddd ssssuuuubbbbssssttttiiiittttuuuuttttiiiioooonnnnssss ffffrrrroooommmm yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  426.  
  427.      The _p_e_r_l__e_v_a_l__s_v() function lets us evaluate strings of Perl code, so we
  428.      can define some functions that use it to "specialize" in matches and
  429.      substitutions: _m_a_t_c_h(), _s_u_b_s_t_i_t_u_t_e(), and _m_a_t_c_h_e_s().
  430.  
  431.         I32 match(SV *string, char *pattern);
  432.  
  433.      Given a string and a pattern (e.g., m/clasp/ or /\b\w*\b/, which in your
  434.      C program might appear as "/\\b\\w*\\b/"), _m_a_t_c_h() returns 1 if the
  435.      string matches the pattern and 0 otherwise.
  436.  
  437.         int substitute(SV **string, char *pattern);
  438.  
  439.      Given a pointer to an SV and an =~ operation (e.g., s/bob/robert/g or
  440.      tr[A-Z][a-z]), _s_u_b_s_t_i_t_u_t_e() modifies the string within the AV at
  441.      according to the operation, returning the number of substitutions made.
  442.  
  443.         int matches(SV *string, char *pattern, AV **matches);
  444.  
  445.      Given an SV, a pattern, and a pointer to an empty AV, _m_a_t_c_h_e_s() evaluates
  446.      $string =~ $pattern in an array context, and fills in _m_a_t_c_h_e_s with the
  447.      array elements, returning the number of matches found.
  448.  
  449.      Here's a sample program, _m_a_t_c_h._c, that uses all three (long lines have
  450.      been wrapped here):
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  467.  
  468.  
  469.  
  470.       #include <EXTERN.h>
  471.       #include <perl.h>
  472.  
  473.       /** my_perl_eval_sv(code, error_check)
  474.       ** kinda like perl_eval_sv(),
  475.       ** but we pop the return value off the stack
  476.       **/
  477.       SV* my_perl_eval_sv(SV *sv, I32 croak_on_error)
  478.       {
  479.           dSP;
  480.           SV* retval;
  481.  
  482.           PUSHMARK(SP);
  483.           perl_eval_sv(sv, G_SCALAR);
  484.  
  485.           SPAGAIN;
  486.           retval = POPs;
  487.           PUTBACK;
  488.  
  489.           if (croak_on_error && SvTRUE(ERRSV))
  490.              croak(SvPVx(ERRSV, PL_na));
  491.  
  492.           return retval;
  493.       }
  494.  
  495.       /** match(string, pattern)
  496.       **
  497.       ** Used for matches in a scalar context.
  498.       **
  499.       ** Returns 1 if the match was successful; 0 otherwise.
  500.       **/
  501.  
  502.       I32 match(SV *string, char *pattern)
  503.       {
  504.           SV *command = NEWSV(1099, 0), *retval;
  505.  
  506.           sv_setpvf(command, "my $string = '%s'; $string =~ %s",
  507.                    SvPV(string,PL_na), pattern);
  508.  
  509.           retval = my_perl_eval_sv(command, TRUE);
  510.           SvREFCNT_dec(command);
  511.  
  512.           return SvIV(retval);
  513.       }
  514.  
  515.       /** substitute(string, pattern)
  516.       **
  517.       ** Used for =~ operations that modify their left-hand side (s/// and tr///)
  518.       **
  519.       ** Returns the number of successful matches, and
  520.       ** modifies the input string if there were any.
  521.       **/
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  533.  
  534.  
  535.  
  536.  
  537.       I32 substitute(SV **string, char *pattern)
  538.       {
  539.           SV *command = NEWSV(1099, 0), *retval;
  540.  
  541.           sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
  542.                    SvPV(*string,PL_na), pattern);
  543.  
  544.           retval = my_perl_eval_sv(command, TRUE);
  545.           SvREFCNT_dec(command);
  546.  
  547.           *string = perl_get_sv("string", FALSE);
  548.           return SvIV(retval);
  549.       }
  550.  
  551.       /** matches(string, pattern, matches)
  552.       **
  553.       ** Used for matches in an array context.
  554.       **
  555.       ** Returns the number of matches,
  556.       ** and fills in **matches with the matching substrings
  557.       **/
  558.  
  559.       I32 matches(SV *string, char *pattern, AV **match_list)
  560.       {
  561.           SV *command = NEWSV(1099, 0);
  562.           I32 num_matches;
  563.  
  564.           sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)",
  565.                    SvPV(string,PL_na), pattern);
  566.  
  567.           my_perl_eval_sv(command, TRUE);
  568.           SvREFCNT_dec(command);
  569.  
  570.           *match_list = perl_get_av("array", FALSE);
  571.           num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/
  572.  
  573.           return num_matches;
  574.       }
  575.  
  576.       main (int argc, char **argv, char **env)
  577.       {
  578.           PerlInterpreter *my_perl = perl_alloc();
  579.           char *embedding[] = { "", "-e", "0" };
  580.           AV *match_list;
  581.           I32 num_matches, i;
  582.           SV *text = NEWSV(1099,0);
  583.  
  584.           perl_construct(my_perl);
  585.           perl_parse(my_perl, NULL, 3, embedding, NULL);
  586.  
  587.           sv_setpv(text, "When he is at a convenience store and the bill comes to some amount like 76 cents, Maynard is aware that there is something he *should* do, something that will enable him to get back a quarter, but he has no idea *what*.  He fumbles through his red squeezey changepurse and gives the boy three extra pennies with his dollar, hoping that he might luck into the correct amount.  The boy gives him back two of his own pennies and then the big shiny quarter that is his prize. -RICHH");
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  599.  
  600.  
  601.  
  602.  
  603.           if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
  604.              printf("match: Text contains the word 'quarter'.\n\n");
  605.           else
  606.              printf("match: Text doesn't contain the word 'quarter'.\n\n");
  607.  
  608.           if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
  609.              printf("match: Text contains the word 'eighth'.\n\n");
  610.           else
  611.              printf("match: Text doesn't contain the word 'eighth'.\n\n");
  612.  
  613.           /** Match all occurrences of /wi../ **/
  614.           num_matches = matches(text, "m/(wi..)/g", &match_list);
  615.           printf("matches: m/(wi..)/g found %d matches...\n", num_matches);
  616.  
  617.           for (i = 0; i < num_matches; i++)
  618.              printf("match: %s\n", SvPV(*av_fetch(match_list, i, FALSE),PL_na));
  619.           printf("\n");
  620.  
  621.           /** Remove all vowels from text **/
  622.           num_matches = substitute(&text, "s/[aeiou]//gi");
  623.           if (num_matches) {
  624.              printf("substitute: s/[aeiou]//gi...%d substitutions made.\n",
  625.                     num_matches);
  626.              printf("Now text is: %s\n\n", SvPV(text,PL_na));
  627.           }
  628.  
  629.           /** Attempt a substitution **/
  630.           if (!substitute(&text, "s/Perl/C/")) {
  631.              printf("substitute: s/Perl/C...No substitution made.\n\n");
  632.           }
  633.  
  634.           SvREFCNT_dec(text);
  635.           PL_perl_destruct_level = 1;
  636.           perl_destruct(my_perl);
  637.           perl_free(my_perl);
  638.       }
  639.  
  640.      which produces the output (again, long lines have been wrapped here)
  641.  
  642.         match: Text contains the word 'quarter'.
  643.  
  644.         match: Text doesn't contain the word 'eighth'.
  645.  
  646.         matches: m/(wi..)/g found 2 matches...
  647.         match: will
  648.         match: with
  649.  
  650.  
  651.  
  652.  
  653.  
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  665.  
  666.  
  667.  
  668.         substitute: s/[aeiou]//gi...139 substitutions made.
  669.         Now text is: Whn h s t  cnvnnc str nd th bll cms t sm mnt lk 76 cnts,
  670.         Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt bck
  671.         qrtr, bt h hs n d *wht*.  H fmbls thrgh hs rd sqzy chngprs nd gvs th by
  672.         thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct mnt.  Th by gvs
  673.         hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH
  674.  
  675.         substitute: s/Perl/C...No substitution made.
  676.  
  677.  
  678.      FFFFiiiiddddddddlllliiiinnnngggg wwwwiiiitttthhhh tttthhhheeee PPPPeeeerrrrllll ssssttttaaaacccckkkk ffffrrrroooommmm yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  679.  
  680.      When trying to explain stacks, most computer science textbooks mumble
  681.      something about spring-loaded columns of cafeteria plates: the last thing
  682.      you pushed on the stack is the first thing you pop off.  That'll do for
  683.      our purposes: your C program will push some arguments onto "the Perl
  684.      stack", shut its eyes while some magic happens, and then pop the
  685.      results--the return value of your Perl subroutine--off the stack.
  686.  
  687.      First you'll need to know how to convert between C types and Perl types,
  688.      with _n_e_w_S_V_i_v() and _s_v__s_e_t_n_v() and _n_e_w_A_V() and all their friends.  They're
  689.      described in the _p_e_r_l_g_u_t_s manpage.
  690.  
  691.      Then you'll need to know how to manipulate the Perl stack.  That's
  692.      described in the _p_e_r_l_c_a_l_l manpage.
  693.  
  694.      Once you've understood those, embedding Perl in C is easy.
  695.  
  696.      Because C has no builtin function for integer exponentiation, let's make
  697.      Perl's ** operator available to it (this is less useful than it sounds,
  698.      because Perl implements ** with C's _p_o_w() function).  First I'll create a
  699.      stub exponentiation function in _p_o_w_e_r._p_l:
  700.  
  701.          sub expo {
  702.              my ($a, $b) = @_;
  703.              return $a ** $b;
  704.          }
  705.  
  706.      Now I'll create a C program, _p_o_w_e_r._c, with a function _P_e_r_l_P_o_w_e_r() that
  707.      contains all the perlguts necessary to push the two arguments into _e_x_p_o()
  708.      and to pop the return value out.  Take a deep breath...
  709.  
  710.          #include <EXTERN.h>
  711.          #include <perl.h>
  712.  
  713.          static PerlInterpreter *my_perl;
  714.  
  715.  
  716.  
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  731.  
  732.  
  733.  
  734.          static void
  735.          PerlPower(int a, int b)
  736.          {
  737.            dSP;                            /* initialize stack pointer      */
  738.            ENTER;                          /* everything created after here */
  739.            SAVETMPS;                       /* ...is a temporary variable.   */
  740.            PUSHMARK(SP);                   /* remember the stack pointer    */
  741.            XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack  */
  742.            XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack  */
  743.            PUTBACK;                      /* make local stack pointer global */
  744.            perl_call_pv("expo", G_SCALAR); /* call the function             */
  745.            SPAGAIN;                        /* refresh stack pointer         */
  746.                                          /* pop the return value from stack */
  747.            printf ("%d to the %dth power is %d.\n", a, b, POPi);
  748.            PUTBACK;
  749.            FREETMPS;                       /* free that return value        */
  750.            LEAVE;                       /* ...and the XPUSHed "mortal" args.*/
  751.          }
  752.  
  753.          int main (int argc, char **argv, char **env)
  754.          {
  755.            char *my_argv[] = { "", "power.pl" };
  756.  
  757.            my_perl = perl_alloc();
  758.            perl_construct( my_perl );
  759.  
  760.            perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
  761.            perl_run(my_perl);
  762.  
  763.            PerlPower(3, 4);                      /*** Compute 3 ** 4 ***/
  764.  
  765.            perl_destruct(my_perl);
  766.            perl_free(my_perl);
  767.          }
  768.  
  769.      Compile and run:
  770.  
  771.          % cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  772.  
  773.          % power
  774.          3 to the 4th power is 81.
  775.  
  776.  
  777.      MMMMaaaaiiiinnnnttttaaaaiiiinnnniiiinnnngggg aaaa ppppeeeerrrrssssiiiisssstttteeeennnntttt iiiinnnntttteeeerrrrpppprrrreeeetttteeeerrrr
  778.  
  779.      When developing interactive and/or potentially long-running applications,
  780.      it's a good idea to maintain a persistent interpreter rather than
  781.      allocating and constructing a new interpreter multiple times.  The major
  782.      reason is speed: since Perl will only be loaded into memory once.
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  797.  
  798.  
  799.  
  800.      However, you have to be more cautious with namespace and variable scoping
  801.      when using a persistent interpreter.  In previous examples we've been
  802.      using global variables in the default package main.  We knew exactly what
  803.      code would be run, and assumed we could avoid variable collisions and
  804.      outrageous symbol table growth.
  805.  
  806.      Let's say your application is a server that will occasionally run Perl
  807.      code from some arbitrary file.  Your server has no way of knowing what
  808.      code it's going to run.  Very dangerous.
  809.  
  810.      If the file is pulled in by perl_parse(), compiled into a newly
  811.      constructed interpreter, and subsequently cleaned out with
  812.      perl_destruct() afterwards, you're shielded from most namespace troubles.
  813.  
  814.      One way to avoid namespace collisions in this scenario is to translate
  815.      the filename into a guaranteed-unique package name, and then compile the
  816.      code into that package using the eval entry in the _p_e_r_l_f_u_n_c manpage.  In
  817.      the example below, each file will only be compiled once.  Or, the
  818.      application might choose to clean out the symbol table associated with
  819.      the file after it's no longer needed.  Using the perl_call_argv entry in
  820.      the _p_e_r_l_c_a_l_l manpage, We'll call the subroutine
  821.      Embed::Persistent::eval_file which lives in the file persistent.pl and
  822.      pass the filename and boolean cleanup/cache flag as arguments.
  823.  
  824.      Note that the process will continue to grow for each file that it uses.
  825.      In addition, there might be AUTOLOADed subroutines and other conditions
  826.      that cause Perl's symbol table to grow.  You might want to add some logic
  827.      that keeps track of the process size, or restarts itself after a certain
  828.      number of requests, to ensure that memory consumption is minimized.
  829.      You'll also want to scope your variables with the my entry in the
  830.      _p_e_r_l_f_u_n_c manpage whenever possible.
  831.  
  832.       package Embed::Persistent;
  833.       #persistent.pl
  834.  
  835.       use strict;
  836.       use vars '%Cache';
  837.       use Symbol qw(delete_package);
  838.  
  839.       sub valid_package_name {
  840.           my($string) = @_;
  841.           $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
  842.           # second pass only for words starting with a digit
  843.           $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
  844.  
  845.           # Dress it up as a real package name
  846.           $string =~ s|/|::|g;
  847.           return "Embed" . $string;
  848.       }
  849.  
  850.  
  851.  
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  863.  
  864.  
  865.  
  866.       sub eval_file {
  867.           my($filename, $delete) = @_;
  868.           my $package = valid_package_name($filename);
  869.           my $mtime = -M $filename;
  870.           if(defined $Cache{$package}{mtime}
  871.              &&
  872.              $Cache{$package}{mtime} <= $mtime)
  873.           {
  874.              # we have compiled this subroutine already,
  875.              # it has not been updated on disk, nothing left to do
  876.              print STDERR "already compiled $package->handler\n";
  877.           }
  878.           else {
  879.              local *FH;
  880.              open FH, $filename or die "open '$filename' $!";
  881.              local($/) = undef;
  882.              my $sub = <FH>;
  883.              close FH;
  884.  
  885.              #wrap the code into a subroutine inside our unique package
  886.              my $eval = qq{package $package; sub handler { $sub; }};
  887.              {
  888.                  # hide our variables within this block
  889.                  my($filename,$mtime,$package,$sub);
  890.                  eval $eval;
  891.              }
  892.              die $@ if $@;
  893.  
  894.              #cache it unless we're cleaning out each time
  895.              $Cache{$package}{mtime} = $mtime unless $delete;
  896.           }
  897.  
  898.           eval {$package->handler;};
  899.           die $@ if $@;
  900.  
  901.           delete_package($package) if $delete;
  902.  
  903.           #take a look if you want
  904.           #print Devel::Symdump->rnew($package)->as_string, $/;
  905.       }
  906.  
  907.       1;
  908.  
  909.       __END__
  910.  
  911.       /* persistent.c */
  912.       #include <EXTERN.h>
  913.       #include <perl.h>
  914.  
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  929.  
  930.  
  931.  
  932.       /* 1 = clean out filename's symbol table after each request, 0 = don't */
  933.       #ifndef DO_CLEAN
  934.       #define DO_CLEAN 0
  935.       #endif
  936.  
  937.       static PerlInterpreter *perl = NULL;
  938.  
  939.       int
  940.       main(int argc, char **argv, char **env)
  941.       {
  942.           char *embedding[] = { "", "persistent.pl" };
  943.           char *args[] = { "", DO_CLEAN, NULL };
  944.           char filename [1024];
  945.           int exitstatus = 0;
  946.  
  947.           if((perl = perl_alloc()) == NULL) {
  948.              fprintf(stderr, "no memory!");
  949.              exit(1);
  950.           }
  951.           perl_construct(perl);
  952.  
  953.           exitstatus = perl_parse(perl, NULL, 2, embedding, NULL);
  954.  
  955.           if(!exitstatus) {
  956.              exitstatus = perl_run(perl);
  957.  
  958.              while(printf("Enter file name: ") && gets(filename)) {
  959.  
  960.                  /* call the subroutine, passing it the filename as an argument */
  961.                  args[0] = filename;
  962.                  perl_call_argv("Embed::Persistent::eval_file",
  963.                                 G_DISCARD | G_EVAL, args);
  964.  
  965.                  /* check $@ */
  966.                  if(SvTRUE(ERRSV))
  967.                      fprintf(stderr, "eval error: %s\n", SvPV(ERRSV,PL_na));
  968.              }
  969.           }
  970.  
  971.           PL_perl_destruct_level = 0;
  972.           perl_destruct(perl);
  973.           perl_free(perl);
  974.           exit(exitstatus);
  975.       }
  976.  
  977.      Now compile:
  978.  
  979.       % cc -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  980.  
  981.      Here's a example script file:
  982.  
  983.  
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  995.  
  996.  
  997.  
  998.       #test.pl
  999.       my $string = "hello";
  1000.       foo($string);
  1001.  
  1002.       sub foo {
  1003.           print "foo says: @_\n";
  1004.       }
  1005.  
  1006.      Now run:
  1007.  
  1008.       % persistent
  1009.       Enter file name: test.pl
  1010.       foo says: hello
  1011.       Enter file name: test.pl
  1012.       already compiled Embed::test_2epl->handler
  1013.       foo says: hello
  1014.       Enter file name: ^C
  1015.  
  1016.  
  1017.      MMMMaaaaiiiinnnnttttaaaaiiiinnnniiiinnnngggg mmmmuuuullllttttiiiipppplllleeee iiiinnnntttteeeerrrrpppprrrreeeetttteeeerrrr iiiinnnnssssttttaaaannnncccceeeessss
  1018.  
  1019.      Some rare applications will need to create more than one interpreter
  1020.      during a session.  Such an application might sporadically decide to
  1021.      release any resources associated with the interpreter.
  1022.  
  1023.      The program must take care to ensure that this takes place _b_e_f_o_r_e the
  1024.      next interpreter is constructed.  By default, the global variable
  1025.      PL_perl_destruct_level is set to 0, since extra cleaning isn't needed
  1026.      when a program has only one interpreter.
  1027.  
  1028.      Setting PL_perl_destruct_level to 1 makes everything squeaky clean:
  1029.  
  1030.       PL_perl_destruct_level = 1;
  1031.  
  1032.       while(1) {
  1033.           ...
  1034.           /* reset global variables here with PL_perl_destruct_level = 1 */
  1035.           perl_construct(my_perl);
  1036.           ...
  1037.           /* clean and reset _everything_ during perl_destruct */
  1038.           perl_destruct(my_perl);
  1039.           perl_free(my_perl);
  1040.           ...
  1041.           /* let's go do it again! */
  1042.       }
  1043.  
  1044.      When _p_e_r_l__d_e_s_t_r_u_c_t() is called, the interpreter's syntax parse tree and
  1045.      symbol tables are cleaned up, and global variables are reset.
  1046.  
  1047.      Now suppose we have more than one interpreter instance running at the
  1048.      same time.  This is feasible, but only if you used the -DMULTIPLICITY
  1049.      flag when building Perl.  By default, that sets PL_perl_destruct_level to
  1050.  
  1051.  
  1052.  
  1053.                                                                        PPPPaaaaggggeeee 11116666
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1061.  
  1062.  
  1063.  
  1064.      1.
  1065.  
  1066.      Let's give it a try:
  1067.  
  1068.       #include <EXTERN.h>
  1069.       #include <perl.h>
  1070.  
  1071.       /* we're going to embed two interpreters */
  1072.       /* we're going to embed two interpreters */
  1073.  
  1074.       #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)"
  1075.  
  1076.       int main(int argc, char **argv, char **env)
  1077.       {
  1078.           PerlInterpreter
  1079.               *one_perl = perl_alloc(),
  1080.               *two_perl = perl_alloc();
  1081.           char *one_args[] = { "one_perl", SAY_HELLO };
  1082.           char *two_args[] = { "two_perl", SAY_HELLO };
  1083.  
  1084.           perl_construct(one_perl);
  1085.           perl_construct(two_perl);
  1086.  
  1087.           perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
  1088.           perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);
  1089.  
  1090.           perl_run(one_perl);
  1091.           perl_run(two_perl);
  1092.  
  1093.           perl_destruct(one_perl);
  1094.           perl_destruct(two_perl);
  1095.  
  1096.           perl_free(one_perl);
  1097.           perl_free(two_perl);
  1098.       }
  1099.  
  1100.      Compile as usual:
  1101.  
  1102.       % cc -o multiplicity multiplicity.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  1103.  
  1104.      Run it, Run it:
  1105.  
  1106.       % multiplicity
  1107.       Hi, I'm one_perl
  1108.       Hi, I'm two_perl
  1109.  
  1110.  
  1111.      UUUUssssiiiinnnngggg PPPPeeeerrrrllll mmmmoooodddduuuulllleeeessss,,,, wwwwhhhhiiiicccchhhh tttthhhheeeemmmmsssseeeellllvvvveeeessss uuuusssseeee CCCC lllliiiibbbbrrrraaaarrrriiiieeeessss,,,, ffffrrrroooommmm yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  1112.  
  1113.      If you've played with the examples above and tried to embed a script that
  1114.      _u_s_e()s a Perl module (such as _S_o_c_k_e_t) which itself uses a C or C++
  1115.      library, this probably happened:
  1116.  
  1117.  
  1118.  
  1119.                                                                        PPPPaaaaggggeeee 11117777
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1127.  
  1128.  
  1129.  
  1130.       Can't load module Socket, dynamic loading not available in this perl.
  1131.        (You may need to build a new perl executable which either supports
  1132.        dynamic loading or has the Socket module statically linked into it.)
  1133.  
  1134.      What's wrong?
  1135.  
  1136.      Your interpreter doesn't know how to communicate with these extensions on
  1137.      its own.  A little glue will help.  Up until now you've been calling
  1138.      _p_e_r_l__p_a_r_s_e(), handing it NULL for the second argument:
  1139.  
  1140.       perl_parse(my_perl, NULL, argc, my_argv, NULL);
  1141.  
  1142.      That's where the glue code can be inserted to create the initial contact
  1143.      between Perl and linked C/C++ routines.  Let's take a look some pieces of
  1144.      _p_e_r_l_m_a_i_n._c to see how Perl does this:
  1145.  
  1146.       #ifdef __cplusplus
  1147.       #  define EXTERN_C extern "C"
  1148.       #else
  1149.       #  define EXTERN_C extern
  1150.       #endif
  1151.  
  1152.       static void xs_init _((void));
  1153.  
  1154.       EXTERN_C void boot_DynaLoader _((CV* cv));
  1155.       EXTERN_C void boot_Socket _((CV* cv));
  1156.  
  1157.       EXTERN_C void
  1158.       xs_init()
  1159.       {
  1160.              char *file = __FILE__;
  1161.              /* DynaLoader is a special case */
  1162.              newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
  1163.              newXS("Socket::bootstrap", boot_Socket, file);
  1164.       }
  1165.  
  1166.      Simply put: for each extension linked with your Perl executable
  1167.      (determined during its initial configuration on your computer or when
  1168.      adding a new extension), a Perl subroutine is created to incorporate the
  1169.      extension's routines.  Normally, that subroutine is named
  1170.      _M_o_d_u_l_e::_b_o_o_t_s_t_r_a_p() and is invoked when you say _u_s_e _M_o_d_u_l_e.  In turn,
  1171.      this hooks into an XSUB, _b_o_o_t__M_o_d_u_l_e, which creates a Perl counterpart
  1172.      for each of the extension's XSUBs.  Don't worry about this part; leave
  1173.      that to the _x_s_u_b_p_p and extension authors.  If your extension is
  1174.      dynamically loaded, DynaLoader creates _M_o_d_u_l_e::_b_o_o_t_s_t_r_a_p() for you on the
  1175.      fly.  In fact, if you have a working DynaLoader then there is rarely any
  1176.      need to link in any other extensions statically.
  1177.  
  1178.      Once you have this code, slap it into the second argument of
  1179.      _p_e_r_l__p_a_r_s_e():
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.                                                                        PPPPaaaaggggeeee 11118888
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1193.  
  1194.  
  1195.  
  1196.       perl_parse(my_perl, xs_init, argc, my_argv, NULL);
  1197.  
  1198.      Then compile:
  1199.  
  1200.       % cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  1201.  
  1202.       % interp
  1203.         use Socket;
  1204.         use SomeDynamicallyLoadedModule;
  1205.  
  1206.         print "Now I can use extensions!\n"'
  1207.  
  1208.      EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd can also automate writing the _x_s__i_n_i_t glue code.
  1209.  
  1210.       % perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
  1211.       % cc -c perlxsi.c `perl -MExtUtils::Embed -e ccopts`
  1212.       % cc -c interp.c  `perl -MExtUtils::Embed -e ccopts`
  1213.       % cc -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e ldopts`
  1214.  
  1215.      Consult the _p_e_r_l_x_s manpage and the _p_e_r_l_g_u_t_s manpage for more details.
  1216.  
  1217. EEEEmmmmbbbbeeeeddddddddiiiinnnngggg PPPPeeeerrrrllll uuuunnnnddddeeeerrrr WWWWiiiinnnn33332222
  1218.      At the time of this writing (5.004), there are two versions of Perl which
  1219.      run under Win32.  (The two versions are merging in 5.005.)  Interfacing
  1220.      to ActiveState's Perl library is quite different from the examples in
  1221.      this documentation, as significant changes were made to the internal Perl
  1222.      API.  However, it is possible to embed ActiveState's Perl runtime.  For
  1223.      details, see the Perl for Win32 FAQ at
  1224.      http://www.perl.com/perl/faq/win32/Perl_for_Win32_FAQ.html.
  1225.  
  1226.      With the "official" Perl version 5.004 or higher, all the examples within
  1227.      this documentation will compile and run untouched, although the build
  1228.      process is slightly different between Unix and Win32.
  1229.  
  1230.      For starters, backticks don't work under the Win32 native command shell.
  1231.      The ExtUtils::Embed kit on CPAN ships with a script called ggggeeeennnnmmmmaaaakkkkeeee, which
  1232.      generates a simple makefile to build a program from a single C source
  1233.      file.  It can be used like this:
  1234.  
  1235.       C:\ExtUtils-Embed\eg> perl genmake interp.c
  1236.       C:\ExtUtils-Embed\eg> nmake
  1237.       C:\ExtUtils-Embed\eg> interp -e "print qq{I'm embedded in Win32!\n}"
  1238.  
  1239.      You may wish to use a more robust environment such as the Microsoft
  1240.      Developer Studio.  In this case, run this to generate perlxsi.c:
  1241.  
  1242.       perl -MExtUtils::Embed -e xsinit
  1243.  
  1244.      Create a new project and Insert -> Files into Project: perlxsi.c,
  1245.      perl.lib, and your own source files, e.g. interp.c.  Typically you'll
  1246.      find perl.lib in CCCC::::\\\\ppppeeeerrrrllll\\\\lllliiiibbbb\\\\CCCCOOOORRRREEEE, if not, you should see the CCCCOOOORRRREEEE
  1247.      directory relative to perl -V:archlib.  The studio will also need this
  1248.  
  1249.  
  1250.  
  1251.                                                                        PPPPaaaaggggeeee 11119999
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1259.  
  1260.  
  1261.  
  1262.      path so it knows where to find Perl include files.  This path can be
  1263.      added via the Tools -> Options -> Directories menu.  Finally, select
  1264.      Build -> Build interp.exe and you're ready to go.
  1265.  
  1266. MMMMOOOORRRRAAAALLLL
  1267.      You can sometimes _w_r_i_t_e _f_a_s_t_e_r _c_o_d_e in C, but you can always _w_r_i_t_e _c_o_d_e
  1268.      _f_a_s_t_e_r in Perl.  Because you can use each from the other, combine them as
  1269.      you wish.
  1270.  
  1271. AAAAUUUUTTTTHHHHOOOORRRR
  1272.      Jon Orwant <_o_r_w_a_n_t@_t_p_j._c_o_m> and Doug MacEachern <_d_o_u_g_m@_o_s_f._o_r_g>, with
  1273.      small contributions from Tim Bunce, Tom Christiansen, Guy Decoux,
  1274.      Hallvard Furuseth, Dov Grobgeld, and Ilya Zakharevich.
  1275.  
  1276.      Doug MacEachern has an article on embedding in Volume 1, Issue 4 of The
  1277.      Perl Journal (http://tpj.com).  Doug is also the developer of the most
  1278.      widely-used Perl embedding: the mod_perl system (perl.apache.org), which
  1279.      embeds Perl in the Apache web server.  Oracle, Binary Evolution,
  1280.      ActiveState, and Ben Sugars's nsapi_perl have used this model for Oracle,
  1281.      Netscape and Internet Information Server Perl plugins.
  1282.  
  1283.      July 22, 1998
  1284.  
  1285. CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  1286.      Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant.  All
  1287.      Rights Reserved.
  1288.  
  1289.      Permission is granted to make and distribute verbatim copies of this
  1290.      documentation provided the copyright notice and this permission notice
  1291.      are preserved on all copies.
  1292.  
  1293.      Permission is granted to copy and distribute modified versions of this
  1294.      documentation under the conditions for verbatim copying, provided also
  1295.      that they are marked clearly as modified versions, that the authors'
  1296.      names and title are unchanged (though subtitles and additional authors'
  1297.      names may be added), and that the entire resulting derived work is
  1298.      distributed under the terms of a permission notice identical to this one.
  1299.  
  1300.      Permission is granted to copy and distribute translations of this
  1301.      documentation into another language, under the above conditions for
  1302.      modified versions.
  1303.  
  1304.  
  1305.  
  1306.  
  1307.  
  1308.  
  1309.  
  1310.  
  1311.  
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.                                                                        PPPPaaaaggggeeee 22220000
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))                                                      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1325.  
  1326.  
  1327.  
  1328.  
  1329.  
  1330.  
  1331.  
  1332.  
  1333.  
  1334.  
  1335.  
  1336.  
  1337.  
  1338.  
  1339.  
  1340.  
  1341.  
  1342.  
  1343.  
  1344.  
  1345.  
  1346.  
  1347.  
  1348.  
  1349.  
  1350.  
  1351.  
  1352.  
  1353.  
  1354.  
  1355.  
  1356.  
  1357.  
  1358.  
  1359.  
  1360.  
  1361.  
  1362.  
  1363.  
  1364.  
  1365.  
  1366.  
  1367.  
  1368.  
  1369.  
  1370.  
  1371.  
  1372.  
  1373.  
  1374.  
  1375.  
  1376.  
  1377.  
  1378.  
  1379.  
  1380.                                                                        PPPPaaaaggggeeee 22221111
  1381.  
  1382.  
  1383.  
  1384.  
  1385.  
  1386.  
  1387.